<!--采购协同-->
<template>
	<div class="m-view-demandPlanDetail m-window" v-loading="loading">
		<el-row :gutter="5">
			<el-col :span="2" class="m-floatRight" v-if="deletedShow">
				<el-button type="primary" @click="saveDemandPlan(1)">发布</el-button>
			</el-col>
			<el-col :span="2" class="m-floatRight" v-if="deletedShow">
				<el-button type="primary" @click="saveDemandPlan(0)">保存</el-button>
			</el-col>
			<el-col :span="2" class="m-floatRight">
				<el-button @click="goBack">返回</el-button>
			</el-col>
		</el-row>
		<el-row :gutter="5">
			<el-form label-width="70px" :inline-message="true" label-position="left">
				<el-col :span="6">
					<el-form-item label="需求单号" class="rightItem">
						<el-input v-model="detailForm.requestNo" disabled></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="7">
					<el-form-item label="公司" class="rightItem">
						<el-input v-model="detailForm.companyName" disabled></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="6">
					<el-form-item label="需求区间" class="rightItem">
						<el-date-picker
							v-model="detailForm.startSdate"
							type="date"
							placeholder="需求开始区间"
							value-format="yyyy-MM-dd"
							disabled
						></el-date-picker>
					</el-form-item>
				</el-col>
				<el-col :span="5">
					<el-date-picker
						v-model="detailForm.startEdate"
						type="date"
						placeholder="需求结束区间"
						value-format="yyyy-MM-dd"
						disabled
					></el-date-picker>
				</el-col>
			</el-form>
		</el-row>
		<div class="m-agTable m-top2">
			<ag-grid-vue
				class="m-agTableContent ag-theme-balham"
				:gridOptions="gridOptions"
				:columnDefs="columnDefs"
				:rowData="rowData"
			></ag-grid-vue>
		</div>
		<el-row :gutter="5" class="footerRow">
			<el-form label-width="70px" :inline-message="true" label-position="left">
				<el-col :span="6">
					<el-form-item label="创建日期" class="rightItem">
						<el-input v-model="detailForm.createDate" placeholder="创建日期" disabled></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="6">
					<el-form-item label="创建人" class="rightItem">
						<el-input v-model="detailForm.creator" disabled></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="6">
					<el-form-item label="发布日期" class="rightItem">
						<el-date-picker
							v-model="detailForm.releaseDate"
							type="date"
							placeholder="发布日期"
							value-format="yyyy-MM-dd"
							disabled
						></el-date-picker>
					</el-form-item>
				</el-col>
				<el-col :span="6">
					<el-form-item label="发布人" class="rightItem">
						<el-input v-model="detailForm.releaser" placeholder="发布人" disabled></el-input>
					</el-form-item>
				</el-col>
			</el-form>
		</el-row>
	</div>
</template>

<script>
import gridOptions from "lesso-common/public/gridOptions";
import { maxDate, minDate } from "@/util/format";
import Vue from "vue";
import Msg from "@/public/message"
/**
 * @group demandPlanList
 * 需求计划
 */
const operator = Vue.extend({
	template: `<span>
		<el-button type="text" @click="delDetails" class="rendererClass" size="mini" v-if="delDetailsShow&&!this.params.node.rowPinned">删除</el-button>
		</span>`,
	data () {
		return {
			delDetailsShow: true,
		};
	},
	mounted () {
		const { editModel, detailForm } = this.params.context.componentParent
		if (editModel == 'view' || detailForm.billState == 1) this.delDetailsShow = false
	},
	methods: {
		delDetails () {
			this.params.context.componentParent.deleteDetails(this.params);
		},
	},
});
export default {
	name: "demandPlanDetail",
	props: {
		// 需求计划明细列表数据
		rowData: {
			type: Array
		},
		// 操作模式,add新增;view查看;edit编辑
		editModel: {
			type: String,
			default: 'add'
		},
		// 需求计划详情主表信息
		mainForm: {
			type: Object
		},
		// 需要删除的明细行
		deletedRows: {
			type: Array
		}
	},
	data () {
		return {
			//  需求计划详情头部信息
			detailForm: {
				requestNo: "",
				companyName: "",
				companyCode: "",
				startSdate: "",
				startEdate: "",
				createDate: "",
				creator: this.$global.user.employeeName,
				releaser: "",
				releaseDate: "",
				billState: ''
			},
			//  表格配置
			gridOptions: {},
			//   列配置
			columnDefs: [],
			//   底部合计行统计数据
			totalAmount: 0,
			// 操作按钮是否显示
			deletedShow: true,
			// 页面加载状态
			loading: false,
		};
	},
	beforeMount () {
		this.gridOptions = {
			...gridOptions(),
			context: {
				componentParent: this,
			},
			pinnedBottomRowData: this.createBottomRow(1, "Bottom"),
			getRowStyle: function (params) {
				if (params.node.rowPinned) {
					return { color: "red", "font-weight": "bold" };
				}
			},
		};
		this.columnDefs = [
			{ headerName: "物料编码", field: "matCode", width: 120 },
			{ headerName: "物料名称", field: "matName", width: 180, tooltipField: 'matName' },
			{ headerName: "需求数量", field: "requestAmount", width: 120 },
			{ headerName: "单位", field: "unitCode", width: 70 },
			{ headerName: "送货区域", field: "area", width: 120, tooltipField: 'area' },
			{
				headerName: "需求日期",
				field: "startSdate",
				width: 120,
				valueFormatter: (params) => {
					if (params.value) return this.$utils.dateFormat("yyyy-MM-dd", params.value);
				}
			},
			{
				headerName: "操作",
				field: "operator",
				width: 90,
				cellRendererFramework: operator,
			},
		];
	},
	created () {
		if (this.editModel == "add") {
			let dates = this.rowData.map((row) => {
				return Date.parse(row.startSdate);
			});
			this.detailForm.startEdate = this.$utils.dateFormat("yyyy-MM-dd", maxDate(dates));
			this.detailForm.startSdate = this.$utils.dateFormat("yyyy-MM-dd", minDate(dates));
			this.detailForm.companyName = this.rowData[0].companyName
			this.detailForm.companyCode = this.rowData[0].companyCode
			this.detailForm.createDate = this.$utils.dateFormat("yyyy-MM-dd", new Date().getTime())
		} else {
			const { releaseDate, createDate } = this.mainForm
			this.detailForm = {
				...this.mainForm,
				releaseDate: releaseDate ? this.$utils.dateFormat("yyyy-MM-dd", releaseDate) : '',
				createDate: createDate ? this.$utils.dateFormat("yyyy-MM-dd", createDate) : ''
			}
			if (this.detailForm.billState == 1 || this.editModel == 'view') {
				// 已发布状态或查看详情时隐藏操作按钮
				this.deletedShow = false
			}
		}
	},
	watch: {
		'rowData': {
			handler: function (newValue, oldValue) {
				this.totalAmount = 0
				newValue.forEach(row => {
					this.totalAmount += Number(row.requestAmount)
				})
				let dates = newValue.map((row) => {
					return Date.parse(row.startSdate);
				});
				this.detailForm.startEdate = this.$utils.dateFormat("yyyy-MM-dd", maxDate(dates));
				this.detailForm.startSdate = this.$utils.dateFormat("yyyy-MM-dd", minDate(dates));
				this.$nextTick(_ => {
					this.gridOptions.api.setPinnedBottomRowData(this.createBottomRow(1, "Bottom"))
				})
			},
			deep: true,
			immediate: true
		}
	},
	components: {},
	methods: {
		/**
		 * @vuese
		 * 创建底部合计栏
		 *
		 * @arg 参数count行数,prefix代表栏位位置
		 */
		createBottomRow (count, prefix) {
			let result = [];
			for (let i = 0; i < count; i++) {
				result.push({
					matName: "合计",
					requestAmount: this.totalAmount,
				});
			}
			return result;
		},
		/**
		 * @vuese
		 * 删除行数据
		 *
		 * @arg 参数为当前行明细
		 */
		deleteDetails (params) {
			// 关闭弹窗方法
			// @arg 参数是当前行明细
			this.$emit('deletedRow', params)
		},
        /**
		 * @vuese
		 * 注册返回事件
		 */
		goBack () {
			// 返回列表方法
			this.$emit('goBack')
		},
        /**
		 * @vuese
		 * 保存需求计划
		 *
		 * @arg 参数为需求计划发布状态
		 */
		saveDemandPlan (state) {
			// state为0保存，1发布
			const { companyName, companyCode, startSdate, startEdate, creator, id } = this.detailForm
			let params = {
				requestbill: {
					companyName,
					companyCode,
					startSdate: `${startSdate} 00:00:00`,
					startEdate: `${startEdate} 00:00:00`,
					billState: state,
					id
				},
				requestmxs: []
			}
			if (this.editModel == 'add') {
				params.requestbill.creator = creator
				params.requestbill.creatorId = this.$global.user.id
				this.rowData.forEach(row => {
					params.requestmxs.push({
						...row,
						startSdate: `${row.startSdate} 00:00:00`,
						creator: creator,
						creatorId: this.$global.user.id
					})
				})
			} else {
				let rowData = [...this.rowData, ...this.deletedRows]
				params.requestbill.modifyer = creator
				params.requestbill.modifyerId = this.$global.user.id
				rowData.forEach(row => {
					params.requestmxs.push({
						...row,
						// id,
						startSdate: `${row.startSdate} 00:00:00`,
						modifyer: creator,
						modifyerId: this.$global.user.id
					})
				})
			}
			if (state == 1) {
				params.requestbill.releaser = creator
				params.requestbill.releaserId = this.$global.user.id
				params.requestmxs.forEach(item => {
					item.releaser = creator
					item.releaserId = this.$global.user.id
				})
			}
			this.loading = true
			this.$http.saveDemandData(params).then(({ data }) => {
				this.loading = false
				if (data.code == 1) {
					// 操作成功返回列表
					// @arg 参数为Boolean,为true时刷新列表
					this.$emit('goBack', true)
					Msg.showSuccessMsg(`${state == 1 ? '发布' : '保存'}成功!`)
				} else {
					Msg.showErrorMsg(data.info)
				}
			}).catch(err => {
				this.loading = false
				Msg.showErrorMsg(err.data.message)
			})
		},
	},
};
</script>

<style lang="less">
.m-view-demandPlanDetail {
	.m-agTable {
		bottom: 70px !important;
	}
	.footerRow {
		position: absolute;
		left: 0;
		right: 0;
		bottom: 0;
	}
}
</style>
